import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { message } from 'antd';

// 创建axios实例
const request: AxiosInstance = axios.create({
  // baseURL: process.env.NODE_ENV === 'production' ? '/api' : '/api',
  baseURL: process.env.BASE_API,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    // 假设后端返回格式为: { code: 200, data: ..., message: '...' }
    if (data.code === '0') {
      return data.data;
    } else {
      // 业务错误
      message.error(data.msg || '请求失败');
      // return Promise.reject(new Error(data.msg || '请求失败'));
    }
  },
  (error: AxiosError) => {
    const { response } = error;
    
    if (response) {
      // 根据状态码处理
      switch (response.status) {
        case 401:
          message.error('未授权，请重新登录');
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 403:
          message.error('权限不足');
          break;
        case 404:
          message.error('请求的资源不存在');
          break;
        case 500:
          message.error('服务器内部错误');
          break;
        default:
          message.error((response.data as any)?.message || '网络错误');
      }
    } else {
      message.error('网络连接错误');
    }
    
    return Promise.reject(error);
  }
);

// 封装常用请求方法
export const http = {
  get: <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
    return request.get(url, { params, ...config });
  },

  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
    return request.post(url, data, config);
  },

  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
    return request.put(url, data, config);
  },

  delete: <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
    return request.delete(url, { params, ...config });
  },

  upload: <T = any>(url: string, file: File, data?: any): Promise<T> => {
    const formData = new FormData();
    formData.append('file', file);
    if (data) {
      Object.keys(data).forEach(key => {
        formData.append(key, data[key]);
      });
    }
    return request.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
};

export default request;